package com.dnxh.util;

import cn.hutool.core.util.StrUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author 枳湫
 * @Time 2022/4/6 20:11
 * @Describe Basic_jar
 **/
public class IpUtil {
	
	private static final String CHINA_Z = "http://ip.chinaz.com";
	private static final Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
	
	/**
	 * 获取本机外网IP
	 * @return 外网IP地址
	 */
	public static String getOutIpV4() {
		String ip = StrUtil.EMPTY;
		
		StringBuilder inputLine = new StringBuilder();
		String read = "";
		URL url = null;
		HttpURLConnection urlConnection = null;
		BufferedReader in = null;
		try {
			url = new URL(CHINA_Z);
			urlConnection = (HttpURLConnection) url.openConnection();
			in = new BufferedReader(new InputStreamReader (urlConnection.getInputStream(), StandardCharsets.UTF_8));
			while ((read = in.readLine()) != null) {
				inputLine.append (read).append ("\r\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		Matcher m = p.matcher(inputLine.toString());
		if (m.find()) {
			ip = m.group(1);
		}
		return ip;
	}
}
